/*
 * Async Treeview 0.1 - Lazy-loading extension for Treeview
 * 
 * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
 * 
 * Copyright (c) 2007 Jörn Zaefferer
 * 
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Revision: $Id$
 * 
 */

;
(function($) {

	function load(settings, root, child, container) {
		function createNode(parent) {
			var current = $("<li/>").attr("id", "deptNo_"+this.deptNo || "")
					.html("<span class='dept' rel='"+this.deptFlag+"' >" + this.deptName + "</span>")
					.appendTo(parent);
			if (this.classes) {
				current.children("span").addClass(this.classes);
			}
			if (this.expanded) {
				current.addClass("open");
			}

		
			if ((this.deptFlag && this.deptFlag != "*" && this.deptNo != "00")
					|| (this.children && this.children.length)) {
				var branch = $("<ul/>").appendTo(current);
				if (this.deptFlag != "*") {
					
					current.addClass("hasChildren");
					createNode.call({
								classes : "placeholder",
								deptName : "&nbsp;",
								children : []
							}, branch);
				}

				if (this.children && this.children.length) {

					$.each(this.children, createNode, [branch])
				}
			}
		}
		$.ajax($.extend(true, {
					url : settings.dept,
					dataType : "json",
					data : {
						deptNo : root.split("_")[1]
					},
					success : function(response) {
						child.empty();
						$.each(response, createNode, [child]);
						$(container).treeview({
									add : child
								});
					}
				}, settings.ajax));

	}

	var proxied = $.fn.treeview;
	$.fn.treeview = function(settings) {
		if (!settings.dept) {
			return proxied.apply(this, arguments);
		}
		var container = this;
		if (!container.children().size())
			load(settings, "deptNo_00", this, container);
		var userToggle = settings.toggle;
		return proxied.call(this, $.extend({}, settings, {
			collapsed : true,
			toggle : function() {
				var $this = $(this);
				if ($this.hasClass("hasChildren")) {
					var childList = $this.removeClass("hasChildren").find("ul");
					load(settings, this.id, childList, container);
				}
				if (userToggle) {
					userToggle.apply(this, arguments);
				}
			}
		}));
	};

})(jQuery);